import 'dart:collection';
import 'dart:ui';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../http/bean/clockin/clock_in.dart';
import '../../../http/bean/clockin/clokin_subdata_type.dart';
import '../../../http/model/clokin_model.dart';
import '../../../manager/user_manager.dart';
import '../../dialog/dailog.dart';
import 'clock_in_ui.dart';

///打卡签记录
class ClockinRecordRoute extends StatefulWidget {
  @override
  _State createState() => _State();
}

class _State extends State<ClockinRecordRoute> {
  ClockinPresenter presenter = ClockinPresenter();

  @override
  void initState() {
    super.initState();
    ClockInUi.mFocusedDay = DateTime.now();
    ClockInUi.mCalendarFormat = CalendarFormat.week;
    presenter?.setState = setState;
    presenter?.GetGroupChekTimeList(context);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    presenter?.datas?.clear();
    presenter?.datas = null;
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    var scaffold = Scaffold(
      backgroundColor: AppColors.backgroundColorWithWhite,
      appBar: AppBar(
        backgroundColor: AppColors.backgroundColorWithWhite,
        elevation: 0,
        leading: AppUi.getBack(context, () {
          return false;
        }, color: Colors.black),
        centerTitle: true,
        leadingWidth: 36,
        titleSpacing: 0,
        //打卡记录
        title: Text(
          AppStrings.of(context).ClockInRecord,
          style: AppStyle.textStyleWithTitle(),
        ),
      ),
      body: Material(color: ColorUtils.parseColor("#F2F2F2"), child: _body(context)),
    );
    return WillPopScope(
      child: scaffold,
      onWillPop: () async {
        return true;
      },
    );
  }

  Widget _body(BuildContext context) {
    if (presenter?.datas == null) {
      return Center(
        child: MaterialButton(
          child: Text(AppStrings.of(context).refresh),
          onPressed: () {
            presenter?.GetGroupChekTimeList(context);
          },
        ),
      );
    }
    List<Widget> _children = [];
    _children.add(_clockStatistical(context)); //打卡迟到早退统计
    _children.add(Container(
      child: ClockInUi.tableCalendar(context, presenter?.setState, presenter),
      color: Colors.white,
    )); //日历
    var mDatas = presenter?.getSelectDatasWithDays();
    if (mDatas != null && mDatas.length > 0) {
      _children.add(SizedBox(
        height: px.x(80),
      ));
      int _index = 0;
      mDatas?.forEach((element) {
        var isShowBar = true; //fixme 是否显示条形竖线;打卡记录只有一个的时候，不显示。
        var isOnWork = true; //是否上班;true 上班；false 下班
        double _top = px.x(80);
        if (_index == 0) {
          _top = 0;
        }
        if (element.isOnWork()) {
          //fixme 只有上班打卡
          isShowBar = false;
          isOnWork = true;
          _children.add(ClockInUi.clockInRecord2(
              context, isShowBar, _top, isOnWork, element));
        } else {
          isShowBar = true;
          isOnWork = true;
          //上班
          _children.add(ClockInUi.clockInRecord2(
              context, isShowBar, 0, isOnWork, element));
          isShowBar = false;
          isOnWork = false;
          _top = 0;
          //下班
          _children.add(ClockInUi.clockInRecord2(
              context, isShowBar, _top, isOnWork, element));
        }
        _index++;
      });
    } else {
      //暂无打卡记录
      _children.add(Container(
        color: Colors.white,
        width: px.screenWidth(),
        alignment: Alignment.center,
        child: Text(AppStrings.of(context).NoClockInRecord),
      ));
    }

    return Scrollbar(
      child: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: _children,
        ),
      ),
    );
  }

  ///打卡迟到早退统计
  Widget _clockStatistical(BuildContext context) {
    TextStyle _textStyle = TextStyle(
        color: Colors.black, fontSize: px.x(80), fontWeight: FontWeight.bold);
    TextStyle _textStyle2 = TextStyle(
      color: ColorUtils.parseColor("#666666"),
      fontSize: px.x(35),
    );
    int lateNum = 0;
    var leaveEarlyNum = 0;
    //print("====================================================================月份数据个数：${presenter?.getSelectDatasWithMonth()?.length}");
    presenter?.getSelectDatasWithMonth()?.forEach((element) {
      if (element.islate()) {
        //迟到
        lateNum++;
      }
      if (element.isleaveEarly()) {
        //早退
        leaveEarlyNum++;
      }
    });
    //迟到
    var row1 = Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Text(
          "${lateNum}",
          style: _textStyle,
        ),
        Padding(
          child: Text(
            AppStrings.of(context).late2,
            style: _textStyle2,
          ),
          padding: EdgeInsets.only(bottom: px.x(20)),
        )
      ],
    );
    //早退
    var row2 = Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Text(
          "${leaveEarlyNum}",
          style: _textStyle,
        ),
        Padding(
          child: Text(
            AppStrings.of(context).leaveEarly2,
            style: _textStyle2,
          ),
          padding: EdgeInsets.only(bottom: px.x(20)),
        )
      ],
    );
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          row1,
          SizedBox(
            width: px.x(89),
          ),
          row2
        ],
      ),
      color: AppColors.backgroundColorWithWhite,
      alignment: Alignment.center,
    );
  }
}

class ClockinPresenter {
  StateSetter? setState = null;
  ClokinHistoricalRecord clokinHistoricalRecord =
      ClokinHistoricalRecord.getClokinSubmit(null, null);
  List<ClockinInfo>? datas = null;

  //按天存储签到数据
  Map<String, List<ClockinInfo>> mapDays = HashMap();

  //按月存储签到数据
  Map<String, List<ClockinInfo>> mapMonth = HashMap();

  ///获取当前选中的日期，获取签到数据（当前选中日期的，签到）
  List<ClockinInfo>? getSelectDatasWithDays() {
    String key = getKeyWithDay(ClockInUi.mFocusedDay);
    return mapDays[key];
  }

  ///根据日期，获取打卡记录。
  List<ClockinInfo>? getDatasWithDateTimeDays(DateTime dateTime) {
    String key = getKeyWithDay(dateTime);
    return mapDays[key];
  }

  ///获取当前选中的月份获取签到数据（当前选中日期的，签到）
  List<ClockinInfo>? getSelectDatasWithMonth() {
    String key = getKeyWithMonth(ClockInUi.onPageChangedDate);
    return mapMonth[key];
  }

  ///数据放入map里的键值。按天
  String getKeyWithDay(DateTime? dateTime) {
    return "${dateTime?.year}${dateTime?.month}${dateTime?.day}"; //yyyyMMdd
  }

  ///数据放入map里的键值。按月
  String getKeyWithMonth(DateTime? dateTime) {
    return "${dateTime?.year}${dateTime?.month}"; //yyyyMMdd
  }

  ///获取签到记录
  GetGroupChekTimeList(BuildContext context) {
    Future.delayed(Duration(milliseconds: 200)).then((value) {
      ClokinModel.GetGroupChekTimeList(context, true, clokinHistoricalRecord,
          (value) {
        if (value != null) {
          if (value.isSuccessForCode()) {
            setState?.call(() {
              datas = value.Data;
              datas?.forEach((element) {
                //按天
                String _dayKey = getKeyWithDay(element.getKeyDateTime());
                List<ClockinInfo>? dayDatas = mapDays[_dayKey];
                if (dayDatas != null) {
                  dayDatas?.add(element);
                } else {
                  dayDatas = [];
                  dayDatas?.add(element);
                  mapDays[_dayKey] = dayDatas;
                }
                //按月
                String _monthKey = getKeyWithMonth(element.getKeyDateTime());
                List<ClockinInfo>? monthDatas = mapMonth[_monthKey];
                if (monthDatas != null) {
                  monthDatas?.add(element);
                } else {
                  monthDatas = [];
                  monthDatas?.add(element);
                  mapMonth[_monthKey] = monthDatas;
                }
              });
            });
          } else {
            AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
          }
        }
      });
    });
  }
}
